<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j login-container page-login">
    <!-- 跳转页面登录 -->
    <div class="login-page">
      <div class="l-header">
        <div class="content">
          <router-link
            to="/"
            class="logo"
          >
            <img
              v-if="webConfigData.pcLogoImgText"
              class="img"
              :src="webConfigData.pcLogoImgText"
              alt
            >
          </router-link>
          <div class="go-register">
            {{ $t('login.notRegisteredYet') }}
            <router-link
              to="/register"
              class="register-btn"
            >
              {{ $t('login.registeredUsername') }}
            </router-link>
          </div>
        </div>
      </div>
      <div
        class="l-content"
        :style="webConfigData.pcLoginBgImg ? {backgroundImage:'url('+webConfigData.pcLoginBgImg+')'} : ''"
      >
        <div class="login">
          <div class="login-box">
            <div class="login-header">
              <div
                :class="['item',loginType===1?'active':'']"
                @click="changeLoginType(1)"
              >
                {{ $t('login.mobileLogin') }}
              </div>
              <div
                :class="['item',loginType===0?'active':'']"
                @click="changeLoginType(0)"
              >
                {{ $t('login.accountLogin') }}
              </div>
            </div>
            <!-- 账号登录 -->
            <div
              v-if="loginType===0"
              class="login-con"
            >
              <div :class="['item','account',errorTips===3?'msg-error':'']">
                <div class="icon" />
                <input
                  v-model="userName"
                  v-input-rule
                  type="text"
                  class="input"
                  maxlength="11"
                  :placeholder="$t('login.enterUsername')"
                  @keyup.enter="login"
                >
                <div
                  class="cancel"
                  data-type="userName"
                  @click="clearInput($event)"
                />
              </div>
              <div
                v-show="errorTips === 3"
                class="error"
              >
                {{ $t('ucPassword.enterCorrectNumber') }}
              </div>
              <div :class="['item','password',errorTips===4?'msg-error':'']">
                <div class="icon" />
                <input
                  v-model="password"
                  v-input-rule
                  type="password"
                  class="input"
                  :placeholder="$t('login.enterPassword')"
                  @keyup.enter="login"
                >
                <div
                  class="cancel"
                  data-type="password"
                  @click="clearInput($event)"
                />
              </div>
              <div
                v-show="errorTips === 4"
                class="error"
              >
                {{ $t('login.enterPassword') }}
              </div>
              <a
                href="javascript:void(0)"
                class="login-button"
                @click="login"
                @keyup="login"
              >{{ $t('login.login') }}</a>
              <div :class="['agree-box',$t('language') === 'en'?'agree-box-en':'']">
                <div class="text">
                  <el-checkbox
                    v-model="isAgree"
                    :true-label="true"
                    :false-label="false"
                  />
                </div>
                <div
                  v-if="serviceTermsSwitch || privacyPolicySwitch"
                  class="text"
                >
                  {{ $t('login.consentOfLoginRepresentative') }}
                  <a
                    v-if="serviceTermsSwitch"
                    href="javaScript:void(0)"
                    class="agreement"
                    @click="toTermsPage(0)"
                  >{{ $t('login.termsOfService') }}</a>
                  <span v-if="privacyPolicySwitch && serviceTermsSwitch">{{ $t('login.and') }}</span>
                  <a
                    v-if="privacyPolicySwitch"
                    href="javaScript:void(0)"
                    class="agreement"
                    @click="toTermsPage(1)"
                  >{{ $t('login.privacyPolicy') }}</a>
                </div>
              </div>
              <div
                v-show="errorTips === 6 && !isAgree"
                class="error"
              >
                {{ $t('login.agreeTerms') }}
              </div>
            </div>
            <!-- /账号登录 -->
            <!-- 手机登录 -->
            <div
              v-if="loginType===1"
              class="login-con"
            >
              <div :class="['item','phone',errorTips===1?'msg-error':'']">
                <div class="icon" />
                <input
                  v-model="mobile"
                  type="text"
                  class="input"
                  oninput="value=value.replace(/[^\d]/g,'')"
                  :placeholder="$t('login.enterUserNumber')"
                  maxlength="11"
                  @keyup.enter="login"
                >
                <div
                  class="cancel"
                  data-type="mobile"
                  @click="clearInput($event)"
                />
              </div>
              <div
                v-show="errorTips === 1"
                class="error"
              >
                {{ $t('register.enterValidPhone') }}
              </div>
              <div :class="['item','code',errorTips===2?'msg-error':'']">
                <div class="icon" />
                <input
                  v-model="validCode"
                  type="text"
                  class="input"
                  :placeholder="$t('login.enterCode')"
                  maxlength="6"
                  :style="{width:$t('language')==='en'?'100px':'150px'}"
                  @keyup.enter="login"
                >
                <a
                  v-show="show"
                  href="javascript:void(0);"
                  class="send-code"
                  :style="{width:$t('language')==='en'?'139px':'89px'}"
                  @click="getCode"
                >{{ $t('login.getCode') }}</a>
                <span
                  v-show="!show"
                  class="send-code"
                  :style="{width:$t('language')==='en'?'139px':'89px'}"
                  style="cursor: not-allowed;"
                >{{ count }} s</span>
              </div>
              <div
                v-show="errorTips === 2"
                class="error"
              >
                {{ $t('login.enterCode') }}
              </div>
              <a
                href="javascript:void(0)"
                class="login-button"
                @click="login"
                @keyup="login"
              >{{ $t('login.login') }}</a>
              <div :class="['agree-box',$t('language') === 'en'?'agree-box-en':'']">
                <div class="text">
                  <el-checkbox
                    v-model="isAgree"
                    :true-label="true"
                    :false-label="false"
                  />
                </div>
                <div
                  v-if="serviceTermsSwitch || privacyPolicySwitch"
                  class="text"
                >
                  {{ $t('login.consentOfLoginRepresentative') }}
                  <a
                    v-if="serviceTermsSwitch"
                    href="javaScript:void(0)"
                    class="agreement"
                    @click="toTermsPage(0)"
                  >{{ $t('login.termsOfService') }}</a>
                  <span v-if="privacyPolicySwitch && serviceTermsSwitch">{{ $t('login.and') }}</span>
                  <a
                    v-if="privacyPolicySwitch"
                    href="javaScript:void(0)"
                    class="agreement"
                    @click="toTermsPage(1)"
                  >{{ $t('login.privacyPolicy') }}</a>
                </div>
              </div>
              <div
                v-show="errorTips === 6 && !isAgree"
                class="error"
              >
                {{ $t('login.agreeTerms') }}
              </div>
            </div>
            <!-- /手机登录 -->

            <div class="login-footer">
              <router-link
                to="/register"
                class="footer-a"
              >
                {{ $t('register.registerNow') }}
              </router-link>
              <router-link
                to="/forget-password"
                class="footer-a"
              >
                {{ $t('login.forgotYourPassword') }}
              </router-link>
            </div>
          </div>
        </div>
      </div>
      <div class="l-footer content">
        <div class="copyright">
          {{ webConfigData.pcCopyright }}
        </div>
      </div>
    </div>
    <!-- /跳转页面登录 -->
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import * as util from '@/utils/index.js'
import { encrypt } from '@/utils/crypto.js'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

const webConfigStore = useWebConfigStore()
const webConfigData = computed(() => webConfigStore.pcConfig) // 网站配置信息
const serviceTermsSwitch = ref(true)
const privacyPolicySwitch = ref(true)
onMounted(() => {
  document.title = $t('login.login')
  http.get('/sys/config/info/getSysServiceSwitch').then(({ data }) => {
    serviceTermsSwitch.value = data.serviceTermsSwitch
    privacyPolicySwitch.value = data.privacyPolicySwitch
  })
})

const loginType = ref(0) // 1-手机登录 0-账号登录
const mobile = ref('')
const validCode = ref('')
const userName = ref('')
const password = ref('')
// 输入错误提示:  1-手机号输入错误  2-验证码输入错误  3-账号输入错误  4-密码输入错误 5-图形验证码错误 6-未同意条款
const errorTips = ref(0)
/**
 * 切换登录方式
 */
const changeLoginType = (val) => {
  loginType.value = val
  errorTips.value = 0
  mobile.value = ''
  validCode.value = ''
  userName.value = ''
  password.value = ''
}

// 验证码相关
const show = ref(true)
const count = ref('')
let timer = null
/**
 * 获取登录验证码
 */
const getCode = () => {
  if (!util.checkPhoneNumber(mobile.value)) {
    errorTips.value = 1
    return
  }
  if (!isAgree.value) {
    errorTips.value = 6
    return
  }
  errorTips.value = 0
  const sendSmsParam = {
    mobile: mobile.value
  }
  http.post('/sms/sendLoginCode', sendSmsParam)
    .then(() => {
      const timeCount = 60
      if (!timer) {
        count.value = timeCount
        show.value = false
        timer = setInterval(() => {
          if (count.value > 0 && count.value <= timeCount) {
            count.value--
          } else {
            show.value = true
            clearInterval(timer)
            timer = null
          }
        }, 1000)
      }
    })
}

const isAgree = ref(true) // 是否同意条款
let isLogging = false // 是否正在登录
/**
 * 登录
 */
const login = util.debounce(() => {
  userName.value = userName.value.trim()
  if (loginType.value === 1) {
    // 手机验证码登录
    if (!util.checkPhoneNumber(mobile.value)) {
      errorTips.value = 1
      return
    } else if (!validCode.value.trim()) {
      errorTips.value = 2
      return
    } else if (!isAgree.value) {
      errorTips.value = 6
      return
    }
  } else {
    // 用户名密码
    if (!util.checkUserName(userName.value)) {
      errorTips.value = 3
      return
    } else if (!password.value.trim()) {
      errorTips.value = 4
      return
    } else if (!isAgree.value) {
      errorTips.value = 6
      return
    }
  }
  errorTips.value = 0
  const data = {
    userName: mobile.value ? mobile.value : userName.value,
    passWord: loginType.value === 0 ? encrypt(password.value) : validCode.value
  }
  if (isLogging) { /* empty */ } else {
    http.post(loginType.value === 0 ? '/login' : '/smsLogin', data).then(({ data }) => {
      isLogging = true
      Cookie.set('bbcToken', data.accessToken)
      const user = {
        nickName: data.nickName == null ? '用户名' : data.nickName,
        userAvatar: data.pic
      }
      userStore.setUser(user)
      // 登录完成后需要获取并更新是否为通联支付（开启通联支付时，会失效所有用户的token）
      http.get('/sys/config/paySettlementType').then(({ data }) => {
        if (data) {
          localStorage.setItem('bbcPaySettlementType', data)
          // 获取完通联支付信息后，再跳转页面，防止未获取完成就跳转页面
          router.push({ path: '/' })
        }
      })
    }).catch((err) => {
      const code = parseInt(err.code)
      if (code === 500) {
        ElMessage.error(err.message)
        mobile.value = ''
        validCode.value = ''
      }
    })
  }
}, 600)

/**
 * 清除输入框内容
 */
const clearInput = (e) => {
  const type = e.target.dataset.type
  switch (type) {
    case 'mobile':
      mobile.value = ''
      break
    case 'userName':
      userName.value = ''
      break
    case 'password':
      password.value = ''
      break
    default:
      break
  }
}

/**
 * 跳转到《服务条款》或《隐私协议》
 */
const toTermsPage = (sts) => {
  router.push({
    path: '/terms-page',
    query: {
      sts
    }
  })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
